package com.atguigu.gmall.payment.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.payment.config.AlipayTemplate;
import com.atguigu.gmall.payment.entity.PaymentInfoEntity;
import com.atguigu.gmall.payment.entity.UserInfo;
import com.atguigu.gmall.payment.interceptor.LoginInterceptor;
import com.atguigu.gmall.payment.service.PaymentService;
import com.atguigu.gmall.payment.vo.PayAsyncVo;
import com.atguigu.gmall.payment.vo.PayVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author Aupt
 * @create 2022-06-15-9:57
 */
@Controller
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @GetMapping("pay.html")
    public String pay(@RequestParam("orderToken") String orderToken, Model model) {

        // 根据订单编号查询订单
        OrderEntity orderEntity = this.paymentService.queryOrderByOrderToken(orderToken);
        if (orderEntity == null) {
            throw new RuntimeException("您要支付的订单不存在！");
        }

        // 判断订单是否属于自己
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = orderEntity.getUserId();
        if (userId != userInfo.getUserId()) {
            throw new RuntimeException("您要支付的订单不属于您！");
        }

        // 判断订单是否属于未支付订单
        if (orderEntity.getStatus() != 0) {
            throw new RuntimeException("当前订单不能支付！");
        }

        model.addAttribute("orderEntity", orderEntity);

        return "pay";

    }


    @GetMapping("alipay.html")
    @ResponseBody
    public String alipay(@RequestParam("orderToken") String orderToken) {

        // 根据订单编号查询订单
        OrderEntity orderEntity = this.paymentService.queryOrderByOrderToken(orderToken);
        if (orderEntity == null) {
            throw new RuntimeException("您要支付的订单不存在！");
        }

        // 判断订单是否属于自己
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = orderEntity.getUserId();
        if (userId != userInfo.getUserId()) {
            throw new RuntimeException("您要支付的订单不属于您！");
        }

        // 判断订单是否属于未支付订单
        if (orderEntity.getStatus() != 0) {
            throw new RuntimeException("当前订单不能支付！");
        }

        try {

            // 调用支付宝接口，打开支付页面
            PayVo payVo = new PayVo();
            payVo.setOut_trade_no(orderToken);
            payVo.setTotal_amount("0.01");
            payVo.setSubject("谷粒商城支付平台");

            // 去支付时，保存支付对账记录
            Long payId = this.paymentService.savePaymentInfo(payVo);
            // 传递公共回传参数
            payVo.setPassback_params(payId.toString());

            return this.alipayTemplate.pay(payVo);

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 支付宝回调方法，只做页面跳转
     *
     * @return
     */
    @GetMapping("pay/success")
    public String paySuccess() {
        //TODO 根据订单编号查询订单

        return "paysuccess";
    }


    @PostMapping("pay/ok")
    @ResponseBody
    public String payOk(PayAsyncVo asyncVo) {

        // 1.验签：验证回调是否是支付宝发起的
        Boolean flag = this.alipayTemplate.checkSignature(asyncVo);

        if (!flag) {
            return "failure";
        }

        // 2.校验业务参数： app_id out_trade_no  total_amount
        String app_id = asyncVo.getApp_id();
        String out_trade_no = asyncVo.getOut_trade_no();
        String total_amount = asyncVo.getTotal_amount();
        String payId = asyncVo.getPassback_params();

        // 查询对账记录
        PaymentInfoEntity paymentInfoEntity = this.paymentService.queryPaymentInfoById(payId);
        if (paymentInfoEntity == null || !StringUtils.equals(app_id, this.alipayTemplate.getApp_id())
                || !StringUtils.equals(out_trade_no, paymentInfoEntity.getOutTradeNo())
                || paymentInfoEntity.getTotalAmount().compareTo(new BigDecimal(total_amount)) != 0) {

            return "failure";
        }

        // 3.校验支付状态：trade_status TRADE_SUCCESS
        if (!StringUtils.equals("TRADE_SUCCESS", asyncVo.getTrade_status())) {
            return "failure";
        }

        // 4.更新对账记录表，更新为已支付状态
        paymentInfoEntity.setTradeNo(asyncVo.getTrade_no());
        paymentInfoEntity.setPaymentStatus(1);
        paymentInfoEntity.setCallbackTime(new Date());
        paymentInfoEntity.setCallbackContent(JSON.toJSONString(asyncVo));
        if (this.paymentService.updatePaymentInfo(paymentInfoEntity) == 0) {
            return "failure";
        }

        // 5.更新订单状态(使用mq发送消息)
        this.rabbitTemplate.convertAndSend("ORDER_EXCHANGE", "order.pay", out_trade_no);

        return "success";
    }


}
